﻿using Microsoft.UI.Xaml.Input;
using System.Windows.Input;

namespace TableViewTest.AttachedProperties
{
    public partial class CommandExtensions
    {
        /// <summary>
        /// 单击属性
        /// </summary>
        public static readonly DependencyProperty ClickProperty = DependencyProperty.RegisterAttached("Click", typeof(ICommand), typeof(CommandExtensions), new PropertyMetadata(false, ClickChanged));
        /// <summary>
        /// 获取单击
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        public static ICommand GetClick(UIElement sender) => (ICommand)sender.GetValue(ClickProperty);
        /// <summary>
        /// 设置单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        public static void SetClick(UIElement sender, ICommand value) => sender.SetValue(ClickProperty, value);
        /// <summary>
        /// 单击命令参数
        /// </summary>
        public static readonly DependencyProperty ClickCommandParameterProperty = DependencyProperty.RegisterAttached("ClickCommandParameter", typeof(object), typeof(CommandExtensions), new PropertyMetadata(null));
        /// <summary>
        /// 获取单击命令参数
        /// </summary>
        /// <param name="sender"></param>
        /// <returns></returns>
        public static object? GetClickCommandParameter(UIElement sender) => sender.GetValue(ClickCommandParameterProperty);
        /// <summary>
        /// 设置单击命令参数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="value"></param>
        public static void SetClickCommandParameter(UIElement sender, object value) => sender.SetValue(ClickCommandParameterProperty, value);
        /// <summary>
        /// 单击更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private static void ClickChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            if (sender is not UIElement uiElement) return;
            uiElement.Tapped += UiElement_Tapped;
        }
        /// <summary>
        /// 单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void UiElement_Tapped(object sender, TappedRoutedEventArgs e)
        {
            if (sender is not UIElement uiElement) return;
            ICommand clickCommand = GetClick(uiElement);
            object clickCommandParameter = GetClickCommandParameter(uiElement) ?? uiElement;
            if (!clickCommand.CanExecute(clickCommandParameter)) return;
            clickCommand.Execute(clickCommandParameter);
        }
    }
}
